package com.usian.wemedia.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.service.WmUserService;
import com.usian.wemedia.mapper.WmUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser>implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        if (StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        QueryWrapper<WmUser> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(WmUser::getName,dto.getName());
        List<WmUser> list=this.list(wrapper);
        if (list!=null&&list.size()>0){
            WmUser wmUser=list.get(0);
            String newPwd= DigestUtils.md5DigestAsHex((dto.getPassword()+wmUser.getSalt()).getBytes());
            //新生成得密码和数据库得密码做比较
            if (wmUser.getPassword().equals(newPwd)){
                //正确   生成token user
                Map<String,Object> map=new HashMap<>();
                map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
                wmUser.setPassword("");
                wmUser.setSalt("");
                map.put("user",wmUser);
                return ResponseResult.okResult(map);
            }else {
                //输入错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.AD_USER_DATA_NOT_EXIST);
        }
    }
}
